const STORAGE_KEYS = require('../configs/STORAGE_KEYS')

let players;

module.exports = {
  addPlayer(player) {
    const players = this.getPlayers()
    const playerNum = this.getPlayerLastNum();
    player.playerNum = playerNum;
    players[playerNum] = player;
    wx.setStorageSync(STORAGE_KEYS.PLAYERS, players)
    this.stepPlayerLastNum(playerNum)
  },
  getPlayers() {
    return players ? players : players = (wx.getStorageSync(STORAGE_KEYS.PLAYERS) || {})
  },
  getPlayersByNums(playerNums) {
    const players = this.getPlayers();
    return playerNums.map(playerNum => players[playerNum]);
  },
  getCurrentPlayers() {
    const currentPlayerNums = wx.getStorageSync(STORAGE_KEYS.CURRENT_PLAYER_NUMS) || [];
    return this.getPlayersByNums(currentPlayerNums);
  },
  getPlayerLastNum() {
    return wx.getStorageSync(STORAGE_KEYS.PLAYERS_LAST_NUM) || 1;
  },
  stepPlayerLastNum(num) {
    return wx.setStorageSync(STORAGE_KEYS.PLAYERS_LAST_NUM, num + 1)
  },
  editPlayer(player) {
    const { playerNum } = player;
    const players = this.getPlayers()
    players[playerNum] = player;
    wx.setStorageSync(STORAGE_KEYS.PLAYERS, players)
  }
}